import {useTableActionRedux} from "@/components/ant-ext-table/redux/HAdminContext";
import {useActionForm,useEdit} from "@/common/hooks";
import HModal from "@/components/ant-ext/HModal";
import {Form} from "antd";
import HFormItem from "@/components/ant-ext/HFormItem";
import SysDepart from "@/api/sys-depart";
import SysNotife, {SysNoticeEntity} from "@/api/sys-notice";
import {TreeSelectElement} from "@/common/zct-types";
import {util} from "@/common/util";
import {Key, useEffect, useState} from "react";

export default function AdminEdit() {
    const [loading, setLoading] = useState(false)
    const [treeData, setTreeData] = useState<TreeSelectElement[]>([]);
    const [expandedOrgCodeKeys, setExpandedOrgCodeKeys] = useState<Key[]>([])
    const {action, reset} = useTableActionRedux<SysNoticeEntity>()
    const {form, key, title} = useActionForm(action, [SysNotife.EDIT], SysNotife.MAPPING)
    const close = () => {
        reset()
        form.resetFields()
    }
    const saveAndFlush = useEdit(key===SysNotife.EDIT ? SysNotife.doEdit : SysNotife.doSave, {
        setLoading: setLoading,
        success: () => {
            reset()
        }
      })
    useEffect(() => {
        SysDepart.selectTree({
                setLoading, success: (data) => {
                    const arr: never[] = []
                    const treeDataMapping = util.TreeSelectDeptMapping(arr, data[0].children)
                    setTreeData(treeDataMapping)
                }
            })
    }, [setTreeData])


    return <>
        <HModal onCancel={close} type={"setUp"} width={500} onOk={form.submit}
                confirmLoading={loading}
                visible={title !== undefined}
                title={title}
        >
            <Form name={"editForm"} form={form} labelCol={{span: 5}}
                  onFinish={() => {
                    saveAndFlush({ body: {...form.getFieldsValue(),type:"0"} })
                    
                  }}>
                <HFormItem label={"id"} name={"id"} hidden={key === SysNotife.ADD}
                           disabled={key !== SysNotife.ADD}/>
                <HFormItem label={"标题"} name={"title"} required/>
                <HFormItem label={"内容"} name={"content"} type={"textarea"}  rows={6} required/>
                <HFormItem label={"所属部门"} name={"deptId"} type={"treeSelect"}
                           treeExpandedKeys={expandedOrgCodeKeys} onTreeExpand={setExpandedOrgCodeKeys}
                           dataSource={treeData}
                           required/>

            </Form>
        </HModal>
    </>
}